import { _decorator, Button, CCBoolean, Component, Node, Input, EventTouch, EventHandler, Tween, tween, Vec3, CCString } from 'cc';
import { Static } from '../../Static';


const { ccclass, property, menu } = _decorator;
@ccclass('BaseButton')
@menu('ISV/按钮组件/BaseButton')

export class BaseButton extends Component {

    /**启用声音 */
    @property({
        tooltip: "启用声音",
    })
    enableSound = true;

    @property({
        visible: function () { return (this as any).enableSound }
    })
    sound = "click"

    /**点击目标 */
    @property(Node)
    target: Node = null

    @property
    scaleTo: Vec3 = new Vec3(0.8, 0.8, 0.8);

    @property
    duration = 0.3

    scaleFrom = new Vec3(1, 1, 1)

    @property(EventHandler) clickEvents: EventHandler[] = []
    @property(EventHandler) touchStartEvents: EventHandler[] = []
    @property(EventHandler) touchCancelEvents: EventHandler[] = []

    onLoad() {
        if (!this.target) {
            this.target = this.node
        }
        this.node.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
        this.node.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
        this.node.on(Input.EventType.TOUCH_CANCEL, this.onTouchCancel, this)
    }


    onDestory() {
        this.node.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
        this.node.off(Input.EventType.TOUCH_END, this.onTouchEnd, this)
        this.node.off(Input.EventType.TOUCH_CANCEL, this.onTouchCancel, this)
    }

    scaleTween: Tween<any> = null

    onTouchStart(event: EventTouch) {
        if (!this.enabled) { return }
        this.clearTween()
        this.scaleTween = tween(this.target).to(this.duration, { scale: this.scaleTo }, { easing: 'expoOut' }).start()
        EventHandler.emitEvents(this.touchStartEvents, this.target)

    }

    onTouchEnd(event: EventTouch) {
        if (!this.enabled) { return }

        this.clearTween()
        this.scaleTween = tween(this.target).to(this.duration, { scale: this.scaleFrom }, { easing: 'expoOut' }).start()
        EventHandler.emitEvents(this.clickEvents, this.target)
        if (this.enableSound) {
            Static.eventTarget.emit(Static.EventType.playSoundEff, this.sound)
            //console.log("播放点击音效")
        }
    }

    clearTween() {
        if (this.scaleTween) {
            this.scaleTween.stop()
            this.scaleTween = null
        }
    }
    onTouchCancel(event: EventTouch) {
        if (!this.enabled) { return }

        this.clearTween()
        this.scaleTween = tween(this.target).to(this.duration, { scale: this.scaleFrom }, { easing: 'expoOut' }).start()
        EventHandler.emitEvents(this.touchCancelEvents, this.target)

    }

}

